﻿//数据列表展现

var ListCommander = function (ListArea) {
    var Handler = "";
    var ControlFile = new Array();
    var DeleteIDs = new Array();
    var Orders = new Array();
    var PageNo = 1;
    var PageSize = 10;
    var SelectType = "";
    var ConditionControls = new Array();
    var Conditions = new Object();
    var Sorts = new Array();
    var ClonePageControl = "";
    var AfterListLoad = function (List) { };
    var BeforeListLoad = function (List) { };

    //保存对象到寄存器里去
    var save = function (Commander) {
        window[ListArea + "Commander"] = Commander;
    };

    //添加一个条件控件，ControlID为控件ID，FilterField为筛选字段
    this.AddConditionControl = function (ControlID, FilterField) {
        ConditionControls.push({
            ControlID: ControlID,
            FilterField: FilterField
        });
        save(this);
    };

    this.ResetCondition = function () {
        Conditions = new Object();
    };

    this.getPageNo = function () {
        return PageNo;
    };

    //配置寄存器
    this.Deploy = function (CommanderConfig) {
        if (CommanderConfig.DeleteIDs) DeleteIDs = CommanderConfig.DeleteIDs;
        if (CommanderConfig.Orders) Orders = CommanderConfig.Orders;
        if (CommanderConfig.Handler) Handler = CommanderConfig.Handler;
        if (CommanderConfig.ControlFile) ControlFile = CommanderConfig.ControlFile;
        if (CommanderConfig.PageNo) PageNo = CommanderConfig.PageNo;
        if (CommanderConfig.PageSize) PageSize = CommanderConfig.PageSize;
        if (CommanderConfig.SelectType) SelectType = CommanderConfig.SelectType;
        if (CommanderConfig.ConditionControls) ConditionControls = CommanderConfig.ConditionControls;
        if (CommanderConfig.Conditions) Conditions = CommanderConfig.Conditions;
        if (CommanderConfig.Sorts) Sorts = CommanderConfig.Sorts;
        if (CommanderConfig.ClonePageControl) ClonePageControl = CommanderConfig.ClonePageControl;
        if (CommanderConfig.AfterListLoad) AfterListLoad = CommanderConfig.AfterListLoad;
        if (CommanderConfig.BeforeListLoad) BeforeListLoad = CommanderConfig.BeforeListLoad;
        save(this);
    };

    //以Json格式获取寄存器
    this.ToJson = function () {
        return {
            Handler: Handler,
            ControlFile: ControlFile,
            DeleteIDs: DeleteIDs,
            Orders: Orders,
            PageNo: PageNo,
            PageSize: PageSize,
            SelectType: SelectType,
            Conditions: Conditions,
            Sorts: Sorts,
            ClonePageControl: ClonePageControl
        };
    };

    //查找并绑定数据对象
    this.Search = function (pageNo) {
        this.ResetCondition();
        $(ConditionControls).each(function (n, o) {
            var val = "";
            var TheConditionControl = $("#" + o.ControlID);
            if (TheConditionControl.attr("type") == "checkbox")
                val = !!TheConditionControl.attr("checked") + "";
            else
                val = TheConditionControl.val();
            if (val != "") Conditions[o.FilterField] = $.trim($("#" + o.ControlID).val());
        });
        if (!pageNo) pageNo = 1;
        this.Deploy({ PageNo: pageNo, Conditions: Conditions });
        DataBind.call(this);
    };

    //获取条件集合
    this.getConditions = function () {
        return Conditions;
    };

    //获取列表展现区域
    this.getListArea = function () {
        return $("#" + ListArea);
    };

    //获取排序集合
    this.getSorts = function () {
        return Sorts;
    };

    //获取复制的翻页
    this.GetClonePageControl = function () {
        return ClonePageControl;
    };

    //清除待删除的对象ID
    this.removeDeleteIDs = function () {
        this.DeleteIDs = new Array();
        save(this);
    };

    //清除命令集合
    this.removeOrders = function () {
        this.Orders = new Array();
        save(this);
    };

    //添加一个筛选条件，name是要筛选的字段，val是筛选值
    this.addCondition = function (name, val) {
        var control = $("<input/>");
        var ControlID = ListArea + "_" + name;
        control.attr("id", ControlID);
        control.hide();
        if ($("#" + ControlID).length > 0) control = $("#" + ControlID);
        else $("body").append(control);
        control.val(val);
        this.AddConditionControl(ControlID, name);
    };

    //设置一个待删除的对象ID
    this.addDeleteID = function (id) {
        DeleteIDs.push(id);
        save(this);
    };

    //设置一个命令
    this.addOrder = function (order) {
        Orders.push(order);
        save(this);
    };

    //添加一个排序，sortName是排序字段，sortType是排序类型，1是顺序排例，-1是倒序排列
    this.AddSort = function (sortName, sortType) {
        var sort = new Object();
        sort.SortName = sortName;
        sort.SortType = sortType;
        Sorts.push(sort);
        save(this);
    };

    this.SetClonePageControl = function (ClonePageControlSelector) {
        ClonePageControl = ClonePageControlSelector;
    };

    this.AfterLoad = function (List) { AfterListLoad(List); }

    this.BeforeLoad = function (List) { BeforeListLoad(List); }
};

//获取寄存器
var getCommander = function (ListArea) {
    return window[ListArea + "Commander"];
};

var CreateCommander = function (ListName) {
    new ListCommander(ListName).Deploy({});
};

//数据绑定
var DataBind = function () {
    var Commander = this;
    var ListArea = Commander.getListArea()
    Commander.BeforeLoad(ListArea);
    var data = Commander.ToJson();
    var functions = arguments;
    $.ajax({
        type: "post",
        url: data.Handler,
        dataType: "text",
        data: {
            Parameters: JSON.stringify(data)
        },
        success: function (result) {
            var list = Commander.getListArea();
            list.html(result);

            list.removeClass("loadingArea");

            SortsBuild(list);
            list.attr("PageControler", list.attr("id"));
            Commander.removeDeleteIDs();
            Commander.removeOrders();
            if (typeof SelectedBind != 'undefined') SelectedBind(list);
            if (typeof window["After" + list.attr("id") + "Load"] != 'undefined')
                window["After" + list.attr("id") + "Load"]();
            Commander.AfterLoad(list);
            var ClonePageControl = Commander.GetClonePageControl();
            if (ClonePageControl != "") {
                var theClonePageControl = list.children(":first");
                if (theClonePageControl.hasClass("pagination"))
                    theClonePageControl.remove();
                $(ClonePageControl).prev().before($(ClonePageControl).clone(true));
            }
        },
        error: function (result) {
            DisplayErrorMsg(Commander.getListArea(), result);
        }
    });
    DisplayLoadProcess(Commander.getListArea());
};

var DisplayLoadProcess = function (list) {
    list.addClass("loadingArea");
    var loading = $("<div id='" + list.attr("id") + "_loading" + "' class='loading'></div>");
    list.append(loading);
    //$.jBox.tip("", "loading");
}

var DisplayErrorMsg = function (list, result) {
    $(".loading").remove("#" + list.attr("id") + "_loading");
    var msg = "<div style=\"margin:10px; position:absolute; top:0; left:0;\">" + result.status + "<br />" + result.statusText + "</div>";
    list.append(msg);
}

//翻页，control是触发翻页的控件，这个很重要，是通过这个找到列表加载区域的
var PageChang = function (PageNo, control) {
    var listControler = $(control).parents("[PageControler]:first");
    var listCommander = getCommander(listControler.attr("PageControler"));
    listCommander.Deploy({ PageNo: PageNo });
    DataBind.call(listCommander);
};

//构建排序表头
var SortsBuild = function (list) {
    list.find("input[type=hidden]").next().bind("click", function () {
        var listCommander = getCommander(list.attr("id"));
        UpdateSort.call(listCommander, this);
        DataBind.call(listCommander);
    });
    TitleBuild(list);
};

//排序状态更新
var UpdateSort = function (sortTitle) {
    var sortName = $(sortTitle).prev().val();
    var Sorts = new Array();
    Sorts = this.getSorts();
    for (var i = 0; i < Sorts.length; i++) {
        if (Sorts[i].SortName == sortName) {
            var sort = Sorts[i];
            Sorts.splice(i, 1);
            sort.SortType *= -1;
            this.AddSort(sort.SortName, sort.SortType);
            return;
        }
    }
    var sort = new Object();
    sort.SortName = sortName;
    sort.SortType = 1;
    this.AddSort(sort.SortName, sort.SortType);
};

//加载排序样式
var TitleBuild = function (list) {
    var listCommander = getCommander(list.attr("id"));
    var Sorts = listCommander.getSorts();
    if (Sorts.length == 0) return;
    list.find("input[type=hidden]").next().each(function (n, o) {
        var SortTitle = $(o);
        var sort = Sorts.slice(-1)[0];
        var SortName = sort.SortName;
        var SortType = sort.SortType;
        if (SortTitle.prev().val() == SortName) {
            if (SortType == -1)
                SortTitle.attr("class", "DESC");
            else
                SortTitle.attr("class", "ASC");
        }
        SortTitle.css("cursor", "pointer");
    });
};